package cn.sourcespro.shiro.util;

import cn.sourcespro.shiro.crudparams.vo.Vo;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.http.HttpStatus;

import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * security
 *
 * @author zhanghaowei
 * @date 2018/7/20
 */
public class RespUtil {

    public static void send(ServletResponse response, String msg, HttpStatus status) throws IOException {
        send(toHttp(response), msg, status);
    }

    public static void send(HttpServletResponse response, String msg, HttpStatus status) throws IOException {

        response.setCharacterEncoding("UTF-8");
        PrintWriter printWriter = response.getWriter();
        response.setContentType("application/json;charset=UTF-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");

        ObjectMapper mapper = new ObjectMapper();
        String respStr;

        respStr = mapper.writeValueAsString(new Vo(msg, status));
        response.setHeader("content-Length", respStr.getBytes().length + "");
        printWriter.write(respStr);
        printWriter.flush();

    }

    public static HttpServletResponse toHttp(ServletResponse response) {
        return (HttpServletResponse) response;
    }

}
